package com.polaris.live.ui.web.js

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.AppUtils
import com.just.agentweb.AgentWeb
import com.lxj.xpopup.XPopup
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.common.util.loading.LoadingUtils
import com.polaris.live.constant.TrackEventConst
import com.polaris.live.constant.UserConst
import com.polaris.live.dialog.ChargeFailureDialog
import com.polaris.live.manager.GooglePayManager
import com.polaris.live.resp.back_resp.PayerRechargePriceListVo
import com.polaris.live.ui.web.WebActivity
import com.polaris.live.utils.TrackHelper
import com.polaris.live.utils.WebAppConfig
import com.polaris.live.utils.WebUtils
import com.polaris.live.utils.route.RouterUtils
import ren.yale.android.cachewebviewlib.WebViewCacheInterceptorInst

/**
 * js交互基类
 *
 * @author Created by lucas on 2023/10/24 11:47
 * @since 1.0.0
 */
abstract class AbstractJsBridgeProxy(
    private val mActivity: WebActivity,
    private val mAgent: AgentWeb,
    private val mUrl: String,
) : LifecycleEventObserver {

    init {
        mActivity.lifecycle.addObserver(this)
    }

    /**
     * 跳转到指定界面
     * 有关页面的跳转关系
     *
     * @param routeUrl 本地页面跳转路由
     */
    open fun directPage(routeUrl: String) {
        if (routeUrl.isNotEmpty()) {
            //本地页面跳转
            if (routeUrl == RouterUtils.Type.KEY_ACTION + "finish") {
                finish()
            } else {
                val pathUrl = RouterUtils.routerGetPath(routeUrl)
                if (pathUrl in RouterUtils.paths) {
                    RouterUtils.killTopActivity(routeUrl, pathUrl)
                } else {
                    RouterUtils.routerGoto(routeUrl)
                }
            }
        }
    }

    /**
     * 清除web缓存
     */
    open fun clearWebCache() {
        mAgent.clearWebCache()
        WebViewCacheInterceptorInst.getInstance().clearCache()
    }

    /**
     * 获取当前版本号
     */
    open val appVersion: String
        get() = AppUtils.getAppVersionCode().toString()

    /**
     * 获取登录用户的accessToken
     */
    open val accessToken: String
        get() = if (WebUtils.isSafeUrl(mUrl)) {
            UserManager.getUser().token ?: ""
        } else {
            ""
        }

    /**
     * 获取应用配置
     */
    open val appConfig: String
        get() = if (WebUtils.isSafeUrl(mUrl)) {
            WebAppConfig(UserManager.getUser()).toJson()
        } else {
            "{}"
        }

    /**
     * 调用系统Toast输出提示
     */
    open fun toast(toast: String) {
        ToastGravity.showGravity(toast)
    }

    /**
     * 关闭当前H5页面
     */
    open fun finish() {
        if (!mActivity.isFinishing) {
            mActivity.finish()
        }
    }

    /**
     * 显示loading
     */
    open fun showLoading(message: String) {
        LoadingUtils.showLoadingDialog(mActivity, message)
    }

    /**
     * 隐藏loading
     */
    open fun hideLoading() {
        LoadingUtils.dismissLoadingDialog()
    }

    /**
     * 添加右上角菜单
     */
    open fun addRightMenu(url: String, h5Function: String, params: String) {
        mActivity.addRightMenu(url) {
            callJs(h5Function, params)
        }
    }

    /**
     * 添加右上角第二个左边的菜单
     */
    open fun addRightMenu2(url: String, h5Function: String, params: String) {
        mActivity.addRightMenu2(url) {
            callJs(h5Function, params)
        }
    }

    /**
     * 传递用户信息
     */
    open fun getUserInfo(h5Function: String) {
        mActivity.upDataUserInfo {
            val json = if (WebUtils.isSafeUrl(mUrl)) {
                JsonUtils.toJson(UserManager.getUser())
            } else {
                "{}"
            }
            callJs(h5Function, json)
        }
    }

    /**
     * base64保存图片功能
     */
    open fun saveBase64Img(base64Url: String) {
        mActivity.saveBase64Img(base64Url)
    }

    private fun callJs(h5Function: String, params: String) {
        if (h5Function.isEmpty()) {
            return
        }
        mAgent.webCreator.webView.loadUrl(String.format("javascript:%s(%s)", h5Function, params))
    }

    open fun googlePay(params: String) {
        try {
            val vo = JsonUtils.fromJson<PayerRechargePriceListVo>(params)
            if (vo != null) {
                buyShow(vo)
            }
        } catch (_: Throwable) {
        }
    }

    private fun buyShow(item: PayerRechargePriceListVo) {
        TrackHelper.postTrack(
            mActivity,
            TrackEventConst.EVENT_TOPUP_PC,
            params = TrackHelper.rechargeForMap(mutableMapOf("price" to item.price))
        )
        GooglePayManager.buyShow(mActivity,
            item.priceId,
            UserConst.From.UNKNOWN,
            item.payerRechargeRewardsType,
            price = item.price,
            showToast = false,
            onSuccess = {
                mActivity.finish()
            },
            onFailure = {
                XPopup.Builder(mActivity)
                    .isDestroyOnDismiss(true)
                    .asCustom(
                        ChargeFailureDialog(mActivity)
                    ).show()
            })
    }

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
    }
}